<?php

namespace App\Services;

use App\Caches\WechatAccessTokenCache;
use App\Services\WechatApi\WechatApiBase;

class WechatService extends ServiceBase
{
    // 登录凭证校验
    public function code2Session($appid, $secret, $code)
    {
        return WechatApiBase::getInstance()->code2Session($appid, $secret, $code);
    }

    // 获取公众号/小程序全局唯一后台接口调用凭据
    public function getAccessToken($appid, $secret, $refresh = false)
    {
        $info         = WechatAccessTokenCache::getInstance()->get($appid);
        $ctime        = time();
        $expires_time = $info['expires_time'] ?? 0;
        if ($refresh || empty($info) || $expires_time - $ctime < 0) {
            $res = WechatApiBase::getInstance()->getStableAccessToken($appid, $secret);
            if (!$res) {
                return false;
            }

            $info['access_token'] = $res['access_token'];
            $info['expires_in']   = $res['expires_in'];
            $info['expires_time'] = $ctime + $res['expires_in'] - 1;
            WechatAccessTokenCache::getInstance()->update($appid, $info);
        }

        return $info['access_token'];
    }
}
